from flask import render_template, redirect, url_for
from blueprints import post_blueprint
from models import QueryOneInstance, QueryMultipleInstances, Blog, PackInstance, User, Comment, Personal
from tools.decorate import pack_session

@post_blueprint.route('/my/page/blog_control', methods=['GET'])
@pack_session
def get_my_page_of_blog_control(data):
    data['Comment'] = []
    unchecked = PackInstance(QueryMultipleInstances(Blog,{'checked':False,'uid':data['session']['uid']}))
    unpassed = PackInstance(QueryMultipleInstances(Blog,{'checked':True,'passed':False,'uid':data['session']['uid']}))
    passed = PackInstance(QueryMultipleInstances(Blog,{'checked':True,'passed':True,'uid':data['session']['uid']}))

    data['unchecked'] = unchecked
    data['unpassed'] = unpassed
    data['passed'] = passed

    comments = PackInstance(QueryMultipleInstances(Comment,{'uid':data['session']['uid']}))
    data.update(comments)
    for i in data['Comment']:
        user = QueryOneInstance(User,{'id':i['uid']})
        blog = QueryOneInstance(Blog,{'uid':i['uid']})
        i.update(PackInstance(user))
        i.update(PackInstance(blog))

    return render_template('pages/post/blog_control.html',data=data)

@post_blueprint.route('/anyone/page/blog/<int:pid>', methods=['GET'])
@pack_session
def get_anyone_page_of_blog(data):
    data['Comment']=[]
    blog = QueryOneInstance(Blog,{'id':data['route']['pid']})
    comments = QueryMultipleInstances(Comment,{'pid':blog.id})
    author = QueryOneInstance(User,{'id':blog.uid})
    author_personal = QueryOneInstance(Personal,{'uid':author.id})

    data.update(PackInstance(author_personal))
    data.update(PackInstance(author))
    data.update(PackInstance(blog))
    data.update(PackInstance(comments))

    for i in data['Comment']:
        personal = QueryOneInstance(Personal,{'uid':i['uid']})
        user = QueryOneInstance(User,{'id':i['uid']})
        i.update(PackInstance(personal))
        i.update(PackInstance(user))

    data['writeable']= (blog.checked and blog.passed)

    return render_template('pages/post/blog.html',data=data)

@post_blueprint.route('/my/page/create/blog', methods=['GET'])
@pack_session
def get_my_page_of_create_blog(data):
    data['Blog']=[]
    return render_template('pages/post/create_or_update_blog.html',data=data)


@post_blueprint.route('/my/page/update/blog/<int:pid>', methods=['GET'])
@pack_session
def get_my_page_of_update_blog(data):
    ins = QueryOneInstance(Blog,{'id':data['route']['pid']})

    #编辑post非自己的，或者不存在
    if ins is None or ins.uid != data['session']['uid']:
        return redirect(url_for('post.get_my_page_of_create_blog'))

    data.update(PackInstance(ins))
    return render_template('pages/post/create_or_update_blog.html',data=data)